<template>
  <div>
    <!-- <vm-title title="添加产品"
              :marginBottom="true"
              @titleClick="goNew"></vm-title> -->

    <vm-status v-if="showStatus"
               empty-text="暂无产品"
               class="bg-white"
               :type="totalPages === -1 ? 'error' : 'empty'"></vm-status>

    <list v-else
          ref="list"
          :showRefresh="true"
          :showLoadMore="showLoadMore"
          @refresh="refresh"
          @loadMore="loadmore"
          loadmoreoffset="100"
          style="margin-top: 20px;">
      <cell v-for="(item, index) in data"
            :key="index">
        <div class="cell"
             @click="showEdit(item)">
          <image class="p-img"
                 :src="item.image"></image>
          <div class="flex">
            <text class="mb-1">{{item.productName}}</text>
            <text class="subtext">{{item.des}}</text>
            <text class="subtext">参考单价: {{item.unitPrice || '-'}}{{item.unitStr}}</text>
            <text class="subtext">产品数量: {{item.yearOutput || '-'}}</text>
            <text class="subtext">养殖类型: {{item.baseTypeName || '-'}}</text>
          </div>
        </div>
      </cell>
    </list>

    <vm-mask height="200"
             width="560"
             ref="editMask"
             :top="200"
             :show-close="true"
             :show.sync="editVisible"
             @close="editClose">
      <textarea class="textarea"
                ref="editTextarea"
                v-model="productName"
                rows="2"
                placeholder="填写产品名称"></textarea>
      <text class="textarea-btn"
            @click="onEditConfirm">确认</text>
    </vm-mask>

  </div>
</template>
<script>
import VmStatus from '../../components/vm-status.vue'
import VmTitle from '../../components/vm-title.vue'
import VmMask from '../../components/vm-mask.vue'
import {
  STORAGE_FARM
} from '../../plugins/constant'
import {
  enumBreedType
} from '../../plugins/enumChick'

export default {
  components: { VmStatus, VmTitle, VmMask },
  props: {},
  data: () => ({
    params: {
      index: 1,
      size: 10,
      'supplier_id.eq': ''
    },
    data: [],
    totalPages: 2,
    enumBreedType,

    productName: '',
    productId: '',
    categoryId: '',
    editVisible: false
  }),
  computed: {
    showLoadMore() {
      return this.totalPages > this.params.index
    },
    showStatus() {
      return this.totalPages === -1 || !this.data.length
    }
  },
  watch: {},
  eros: {
    beforeBackAppear(params) {
      if (!params) { return }
      if (params.type === 1) {
        this.refresh()
        return
      }
    }
  },
  created() {
    this.getFarm()
  },
  methods: {
    getFarm() {
      this.farm = this.$storage.getSync(STORAGE_FARM) || {}
      if (this.farm.id) {
        this.params['supplier_id.eq'] = this.farm.id
        this.refresh()
      } else {
        this.$notice.toast({ message: '没有鸡场信息' })
        this.$router.setBackParams({ type: 1 })
      }
    },
    refresh() {
      this.params.index = 1
      this.getData().then(res => {
        this.data = res
      }).finally(() => {
        this.$refs["list"].refreshEnd()
      })
    },
    loadmore() {
      this.getData().then(res => {
        this.data.push(...res)
      }).finally(() => {
        this.$refs["list"].loadMoreEnd()
      })
    },
    getData() {
      return new Promise((resolve, reject) => {
        this.$http({
          method: 'GET',
          name: 'industrial.farm.product',
          data: {
            start: this.params.index,
            size: this.params.size,
            farmId: this.farm.id,
            freeze: 0,
            shelvesStatus: 1,
            isDelete: 0
          },
          errorMsg: '获取产品失败'
        }).then(res => {
          this.params.index++
          this.totalPages = res && res.totalPages || 0
          const data = (res && res.data) || []
          resolve(data.map(this.convert))
        }).catch(err => {
          this.totalPages = -1
          reject(err)
        })

        // this.$api.getData({
        //   server: 'agr_chain',
        //   table: 'supplier_product_view',
        //   params: this.params
        // }).then(res => {
        //   this.params.index++
        //   this.totalPages = res && res.totalPages || 0
        //   const data = res && res.data || []
        //   resolve(data.map(item => {
        //     const images = this.getImagesFromString(item.product_images)
        //     item.image = images.length && images[0] || 'http://www.vimi8.com/static/img_default.png'
        //     return item
        //   }))
        // }).catch(err => {
        //   this.totalPages = -1
        //   this.$notice.toast({ message: '获取产品失败' })
        //   reject(err)
        // })
      })
    },
    convert(item) {
      if (item.productImageList && item.productImageList.length) {
        item.image = `${item.productImageList[0]}?x-oss-process=image/resize,m_fill,h_100,w_100`
      } else {
        item.image = 'http://www.vimi8.com/static/img/img_default.png'
      }
      item.unitStr = item.unit ? `元/${item.unit}` : ''
      item.marketTime = item.marketTime ? item.marketTime.substr(0, 10) : ''
      return item
    },
    goDetail(row) {
      this.$nav.open({
        name: 'farm.product.detail',
        params: { data: row }
      })
    },
    goNew() {
      this.$nav.open({
        name: 'farm.product.new',
        params: {}
      })
    },
    getImagesFromString(images) {
      if (typeof images === 'string') {
        images = images.replace(/^\["(\S*)"\]$/, '$1').split('","')
      }
      return (images && images.length) ? images.filter(img => !!img) : []
    },
    // 修改
    showEdit(product) {
      this.productId = product.id
      this.productName = product.productName
      this.categoryId = product.categoryId
      this.editVisible = true
      setTimeout(() => {
        const ref = this.$refs.editTextarea
        ref && ref.focus()
      }, 30)
    },
    onEditConfirm() {
      if (!this.productName) {
        return this.$notice.toast({ message: '请输入产品名称' })
      }
      this.$notice.loading.show('修改中...')
      this.$http({
        method: 'PUT',
        name: 'industrial.product.put',
        data: {
          id: this.productId,
          productName: this.productName,
          producerId: this.farm.id,
          categoryId: this.categoryId
        },
        errorMsg: '修改产品失败'
      }).then(res => {
        this.$notice.toast({ message: '修改产品成功' })
        this.$refs.editMask.hide()
        this.editClose()
        this.refresh()
      }).finally(() => {
        this.$notice.loading.hide()
      })
    },
    editClose() {
      this.$tools.resignKeyboard()
    }
  }
}
</script>
<style lang="scss" scoped>
@import "../../css/variables.scss";

.text-muted {
  color: #999;
}
.mb-3 {
  margin-bottom: 30px;
}
.mb-1 {
  margin-bottom: 10px;
}
.cell {
  flex-direction: row;
  margin-left: 20px;
  margin-right: 20px;
  margin-bottom: 20px;
  padding: 20px;
  border-radius: 6px;
  background-color: #fff;
}
.flex {
  flex: 1;
}
.subtext {
  font-size: 28px;
  color: #999;
  margin-bottom: 5px;
}
.p-img {
  width: 160px;
  height: 160px;
  margin-right: 20px;
}

.textarea {
  font-size: 28px;
  color: #333;
  height: 100px;
  padding: 20px;
  border-width: 1px;
  border-color: $border-color;
  tint-color: #999;
}
.textarea-btn {
  height: 100px;
  line-height: 100px;
  text-align: center;
}
</style>
